//
//  AuthViewModel.swift
//  Twitter
//
//  Created by Hoa.wang on 2022/4/6.
//

import SwiftUI
import ParseSwift

@MainActor
class AuthViewModel: ObservableObject {
    
    @Published var didAuthenticateUser = false

    @Published var currentUser: User?
    private var tempUserSession: User?

    private let service = UserService()
    
    init() {
        self.currentUser = User.current
        self.fetchUserInfo()
    }
    
    func login(withUsername username: String,
               password: String) async {
        
        guard let result = try? await User.login(username: username.lowercased(), password: password) else {
            print("DEBUG: Failed to login with error")
            return }
        
        self.currentUser = result
        fetchUserInfo()
    }
    
    func register(withEmail email: String,
                  password: String,
                  fullname: String,
                  username: String) async {
        
        guard let result = try? await User.signup(username: username.lowercased(), password: password) else {
            print("DEBUG: Failed to reigster with error")
            return
        }
        
        tempUserSession = result
        
        tempUserSession?.email = email
        tempUserSession?.fullname = fullname
        
        guard let user = try? await tempUserSession?.save() else {
            print("DEBUG: Failed to save email & fullname with error")
            return
        }
        
        tempUserSession = user
        
        didAuthenticateUser = true
    }
    
    func signOut() {
        
        User.logout { _ in
            
        }
        
        self.tempUserSession = nil
        self.tempUserSession = nil
        self.currentUser = nil
        
        didAuthenticateUser = false
    }
    
    func uploadProfileImage(_ image: UIImage) async {
        let profilePic = ParseFile(name: "avatar.png", data: image.pngData()!)
        tempUserSession?.profileImage = profilePic
        guard let user = try? await tempUserSession?.save() else {
            print("DEBUG: Failed to save image.")
            return
        }
        
        currentUser = user
        fetchUserInfo()
    }
    
    func fetchUserInfo() {
        
        self.currentUser?.fetch { result in
            switch result {
            case .success(let user):
                self.currentUser = user
            case .failure(let error):
                print("DEBUG: Failed to fetch userinfo with error: \(error.localizedDescription)")
            }
        }
        
    }
}
